package com.lan.utils;

import com.lan.entity.sys.User;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.Date;

/**
 * JWT工具类.
 *
 * 用于生成token
 * */
public class JWTUtil {

    /**
     * token过期时间.
     * 分*秒
     * */
    private static final Long TOKEN_EXPIRE_TIME = (long) 1000*60*30;
    /**
     * 加密参数.
     * */
    private static final String SIGN = "721-20260301-@#$%";

    /**
     * 获取token.
     *
     * @param user 登录人
     * @return [token]
     */
    public static String getToken(final User user) {
        try {
            final Date expireTime = new Date(System.currentTimeMillis() + TOKEN_EXPIRE_TIME);
            final Algorithm alg = Algorithm.HMAC256(SIGN);
            return JWT.create()
                    .withClaim("account", user.getAccount())
                    .withClaim("password", user.getPassword())
                    .withExpiresAt(expireTime)
                    .sign(alg);
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }

    /**
     * token校验.
     *
     * @param token token
     */
    public static void tokenVerify(final String token) {
        final Algorithm alg = Algorithm.HMAC256(SIGN);
        final JWTVerifier verifier = JWT.require(alg)
                .build();
        verifier.verify(token);
    }

    /**
     * 通过token获取登陆人账户.
     *
     * @param token token
     */
    public static String getAccountByToken(final String token) {
        final Algorithm alg = Algorithm.HMAC256(SIGN);
        final JWTVerifier verifier = JWT.require(alg)
                .build();
        DecodedJWT decodedJWT = verifier.verify(token);
        return decodedJWT.getClaim("account").asString();
    }
}
